// Disable no-unused-vars, broken for spread args
/* eslint no-unused-vars: off */
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
import { ISplitPdfInterface } from './tools';

export type Channels = 'ipc-example';

const electronHandler = {
  ipcRenderer: {
    sendMessage(channel: Channels, ...args: unknown[]) {
      ipcRenderer.send(channel, ...args);
    },
    on(channel: Channels, func: (...args: unknown[]) => void) {
      const subscription = (_event: IpcRendererEvent, ...args: unknown[]) =>
        func(...args);
      ipcRenderer.on(channel, subscription);

      return () => {
        ipcRenderer.removeListener(channel, subscription);
      };
    },
    once(channel: Channels, func: (...args: unknown[]) => void) {
      ipcRenderer.once(channel, (_event, ...args) => func(...args));
    },
  },

  // 打开文件目录选择对话框
  openDirDialog: async (options: any) => {
    return ipcRenderer.invoke('open-dir-dialog', options);
  },

  // 拆分pdf

  splitPdfByPageNo: async (splitPatams: ISplitPdfInterface) => {
    return ipcRenderer.invoke('split-pdf-by-page-no', splitPatams);
  },

  // 监听导航
  onNativate: async (callback: (...args: any[]) => void) => {
    ipcRenderer.on('navigate', callback);
  },
  // 创建AI窗口
  createAIWindow: async (width: number = 400, height: number = 300) => {
    return ipcRenderer.invoke('create-ai-window', { height, width });
  },

  // 主窗口发送消息
  sendMessageToAIWindow: async (message: string) => {
    try {
      const res = await ipcRenderer.invoke('main-window-send-message', message);
      return res; // 返回响应数据
    } catch (error) {
      console.error('请求出错:', error);
    }
  },
  // ai渲染窗口监听主进程发送来的消息
  onMsgFromMainWindowThenReturn: async (callback: (...args: any[]) => void) => {
    ipcRenderer.on('message-to-ai-from-main-window', (event, arg) => {
      callback(arg);
    });
  },
};

contextBridge.exposeInMainWorld('electronAPI', electronHandler);

export type ElectronHandler = typeof electronHandler;
